<?php

/**
 * Helpers 
 * Arquivo de ajuda para algumas funções usadas no site.
 * @package Helpers
 * @name Helpers Scripts
 * @category Utils
 */

/**
 * Header Init
 * Inicialização do arquivos,css,javascripts no template
 * @return $header_css_js  retorna conteúdo para serem adicionados ao header do template do sistema.
 */
function header_init() {


    $ctr = & get_instance();
    $files = $ctr->get_header_js();
    $styles = $ctr->get_header_css();
    $files_ie9 = $ctr->get_ie9_js();
    $css_ie9 = $ctr->get_ie9_js();
    $js = '';

    if (count($styles)) {

        foreach ($styles as $item) {
            $file = str_replace(base_url(), '/', base_url(FOLDER_CSS . str_replace('.css', '', $item['file']) . '.css'));
            $js .= '<link href= "' . $file . '" media="all" rel="stylesheet"/>' . PHP_EOL;
        }
    }
    $js .= '<script type="text/javascript"> var url_site = "' . site_url() . '", url_base ="' . base_url() . '"; </script>' . PHP_EOL;

    if (count($files)) {

        foreach ($files as $item) {
            $file = str_replace(base_url(), '/', base_url(FOLDER_JS . str_replace('.js', '', $item['file']) . '.js'));
            $js .= '<script src="' . $file . '" type="text/javascript"></script>' . PHP_EOL;
        }
    }

    $js .= ' <!--[if lt IE 9]>';
    if ($css_ie9) {

        foreach ($css_ie9 as $item) {
            $file = str_replace(base_url(), '/', base_url(FOLDER_CSS . str_replace('.css', '', $item['file']) . '.css'));
            $js .= '<link href= "' . $file . '" media="all" rel="stylesheet"/>' . PHP_EOL;
        }
    }
    if ($files_ie9) {
        foreach ($files_ie9 as $item) {
            $file = str_replace(base_url(), '/', base_url(FOLDER_JS . str_replace('.js', '', $item['file']) . '.js'));
            $js .= '<script src="' . $file . '" type="text/javascript"></script>' . PHP_EOL;
        }
    }

    $js .='<![endif]-->';




    echo $js;
}

function web_dir() {
    $ctr = & get_instance();
    return $ctr->config->item('web_dir');
}

/**
 * helper footer_init <br>
 * Inicialização do arquivos,css,javascripts no template rodapé. 
 * @author Carlos o Carvalho
 * @version 0.0.2 
 * @return (string) retorna conteúdo para serem adicionados ao header do template do sistema.
 */
function footer_init() {


    $ctr = & get_instance();
    $files = $ctr->get_footer_js();
    $styles = $ctr->get_footer_css();

    $js = '';

    if ($styles) {

        foreach ($styles as $item) {
            $file = str_replace(base_url(), '/', base_url(FOLDER_CSS . str_replace('.css', '', $item['file']) . '.css'));
            $js .= '<link href= "' . $file . '" media="all" rel="stylesheet"/>' . PHP_EOL;
        }
    }


    if ($files) {

        foreach ($files as $item) {
            $file = str_replace(base_url(), '/', base_url(FOLDER_JS . str_replace('.js', '', $item['file']) . '.js'));
            $js .= '<script src="' . $file . '" type="text/javascript"></script>' . PHP_EOL;
        }
    }




    echo $js;
}

if (!function_exists('to_url_friend')) {

    /**
     * helper para converter dados em url's amigaveis.
     * @version 0.0.1  
     * @param string $str url que será convertida
     * @param string $search caracter para ser procurado na url enviada.
     * @param string $replace caracter que substituirá o caracter procurado enviado no segundo parametro.
     * @return (string) retorna url amigavel para browsers
     */
    function to_url_friend($str, $search = '_', $replace = '-') {


        /* debut modif */
        $str = (string) htmlspecialchars_decode($str);

        $caracteres_speciaux = array(
            "¥" => "Y",
            '&#231;' => 'c',
            '&aacute;' => 'a',
            '&Aacute;' => 'a',
            '&acirc;' => 'a',
            '&Acirc;' => 'a',
            '&agrave;' => 'a',
            '&Agrave;' => 'a',
            '&egrave;' => 'e',
            '&Egrave;' => 'e',
            '&eacute;' => 'e',
            '&Eacute;' => 'e',
            '&ecirc;' => 'e',
            '&Ecirc;' => 'e',
            '&uacute;' => 'u',
            '&Uacute;' => 'u',
            '&oacute;' => 'o',
            '&Oacute;' => 'o',
            '&ocirc;' => 'o',
            '&Ocirc;' => 'o',
            '&#45;' => ' ',
            "µ" => "u", "À" => "A", '&atilde;' => 'a',
            '&ccedil;' => 'c',
            "Á" => "A", "Â" => "A",
            "Ã" => "A", "Ä" => "A", "Å" => "A", "Æ" => "A",
            "Ç" => "C", "È" => "E", "É" => "E", "Ê" => "E",
            "Ë" => "E",
            "Ì" => "I",
            "Í" => "I",
            "Î" => "I", "Ï" => "I", "Ð" => "D", "Ñ" => "N",
            "Ò" => "O", "Ó" => "O", "Ô" => "O",
            "Õ" => "O", "Ö" => "O", "Ø" => "O", "Ù" => "U", "Ú" => "U", "Û" => "U",
            "Ü" => "U", "Ý" => "Y", "ß" => "s", "à" => "a", "á" => "a", "â" => "a", "ã" =>
            "a", "ä" => "a", "å" => "a", "æ" => "a",
            "ç" => "c", "è" => "e", "é" => "e", "ê" => "e", "ë" => "e", "ì" => "i", "í" => "i", "î" => "i", "ï" => "i", "ð" => "o", "ñ" => "n", "ò" => "o", "ó" => "o", "ô" => "o", "õ" => "o", "ö" => "o", "ø" => "o", "ù" => "u", "ú" => "u", "û" => "u", "ü" => "u", "ý" => "y", "ÿ" => "y", "€" => "e");

        $str = strtr($str, $caracteres_speciaux);

        /* fin modif */

        $trans = array(
            $search => $replace,
            "\s+" => $replace,
            "[^a-z0-9" . $replace . "]" => '',
            $replace . "+" => $replace,
            $replace . "$" => '',
            "^" . $replace => ''
        );

        $str = strip_tags(strtolower($str));

        foreach ($trans as $key => $val) {
            $str = preg_replace("#" . $key . "#", $val, $str);
        }


        return trim(stripslashes($str), '\\');
    }

}

/**
 * helper para ordenar Array pelos subarrays, pelos indices associativos.  
 * @version 0.0.1  
 * @param string $a array com subarrays.
 * @param string $subkey indice para ordernar.
 * @param string $order ordernacao ASC|DESC
 * @return (array)  retorna novo array com valores ordernados.
 * @example <br/>
 * ----------------------------------------------------------------------------------------------------<br>
 * $array = array(
 *         array('file'=>'filename_css.css','order'=>4),
 *         array('file'=>'filename_css_1.css','order'=>3),
 *         array('file'=>'filename_css.css','order'=>1)
 *     );
 * <br/>
 * $new_arr = subvalSort($array,'order','ASC');
 * --output-- <br/>
 * $new_arr = array(
 *         array('file'=>'filename_css.css','order'=>1),
 *         array('file'=>'filename_css_1.css','order'=>3),
 *         array('file'=>'filename_css.css','order'=>4)
 *         
 *         
 *     );<br>
 * --------------------------------------------------------------------------------------------------------    
 */
function subvalSort($a, $subkey, $order = null) {


    if (count($a) != 0 || (!empty($a))) {
        foreach ($a as $k => $v)
            $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]);
        if ($order == null || $order == 'ASC')
            asort($b);
        else if ($order == 'DESC')
            arsort($b);
        foreach ($b as $key => $val)
            $c[] = $a[$key];

        return $c;
    }
}

/**
 * Add JS
 * 
 * helper para adicionar links de arquivos javascript ao template.
 * @param string $file arquivo que será adicionado ao link
 * @param string $pos em que posição o arquivo será carregado  header|footer
 * @param int $priority  prioridade no carregamento da pagina.
 * 
 */
function add_js($file, $pos = 'footer', $priority = 9) {
    $ci = & get_instance();
    $ci->add_js($file, $pos, $priority);
}

function add_css($file, $pos = 'header', $priority = 9) {
    $ci = & get_instance();
    $ci->add_css($file, $pos, $priority);
}

function add_image($name, $extra = '') {
    return '<img src="' . base_url(FOLDER_IMAGES . $name) . '" ' . $extra . '/>';
}

function get_navbar_topo() {
    $ci = &get_instance();

    $search = isset($ci->gets['q']) ? $ci->gets['q'] : '';
    return '<div id="navbar-menu-topo-geral">
                <div class="navbar-menu-topo-geral-foreground">
                <div class="container navbar-menu-topo ">
                
              
               <div class="row">

                
                   
                       
                            <ul class="navbar-top-site one">
                                <li class="has-link-home"><a href="' . site_url() . '"><span>Pagina Inicial</span></a></li>
                                    <li><span class="barra-separador">|</span></li>
                                <li><a href="' . site_url('quem-somos') . '"><span>Quem somos</span></a></li>
                                    <li><span class="barra-separador">|</span></li>
                                <li><a href="' . site_url('politica-privacidade') . '"><span>Política de Uso</span></a></li>
                                    <li><span class="barra-separador">|</span></li>
                                <li><a href="' . site_url('duvidas') . '"><span>Dúvidas</span></a></li>
                                    <li><span class="barra-separador">|</span></li>
                                <li><a href="' . site_url('contato.html') . '"><span>Contato</span></a></li>
                            </ul>
                    
                   
              
                        
                        <ul class="navbar-top-site two">
                            <li><a data-trigger="newsletter" href="#"><span>Receba Novidades</span></a></li>
                            <li><a href="' . site_url('quero-vender') . '"><span>Quero Vender</span></a></li>
                            <li><a data-trigger="cadastro" href="#" ><span style="color: #fce603;">Cadastre-se</span></a></li>
                            
                        </ul>
                        <div class="navbar-top-site form">
                        <form  action="' . site_url('pesquisar') . '" method="get" class="search-form-topo"  id="formSearchTopo">
                            <div class="row">
                            <div class="col-xs-10  box-input-search">
                            <input type="text" name="q" value="' . $search . '"class="form-control" />
                             </div>
                             
                             <span data-trigger="submit" data-target="#formSearchTopo" class="col-xs-1 icon-pesquisa"><i class="fa fa-search"></i></span>
                              
                             </div>

                        </form>
                        <span data-trigger="submit" data-target="#formSearchTopo" class="col-xs-1 text-form-busca">Buscar</span> 
                        <a  class="icon-home" href="/"><i class="icon-home"><img src="/public/images/icon_home_page.gif" title="Maxbid leilões on line - Ir a pagina inicial" alt="Maxbid leilões on line - Ir a pagina inicial" /></i></a>
                       </div>
                       

               

               
             </div>
            </div>
             </div>
             </div>

';

    /*
      <div class="col-md-7">
      <div id="menu-barra-header-center">
      <ul class="barra-topo2 menu-center-barra">
      <li><a data-trigger="newsletter" href="#"><span>Receba Novidades</span></a></li>
      <li><a href="' . site_url('quero-vender').'"><span>Quero Vender</span></a></li>
      <li><a data-trigger="cadastro" href="#" ><span style="color: #fce603;">Cadastre-se</span></a></li>
      </ul>
      </div>


      <div class="box-form-topo">
      <form  class="search-form-topo">
      <div class="row">
      <div class="col-xs-10  box-input-search">
      <input type="text" class="form-control" />
      </div>

      <span data-trigger="submit" data-target="#formContato" class="col-xs-1 icon-pesquisa"><i class="fa fa-search"></i></span>

      </div>
      </form>

      <a data-trigger="submit" data-target="#formContato" class="icon-home" href="/"><i class="icon-home"><img src="/public/images/icon_home_page.gif" /></i></a>
      </div>


      </div>

     */
}

function form_search() {

    return '<form action="' . site_url('pesquisar') . '" method="get" class="form-search-topo" accept-charset="utf-8" style="position:relative;" id="searchSite">
                                            <input type="text" name="q" placeholder="O que você procura ? " class="form-control "/>
                                            <span role="search" style="position:absolute; top:6px; right:8px; cursor:pointer; color:#f9b815; z-index:30;">
                                                <i class="glyphicon glyphicon-search"></i></span>
                                        </form>    ';
}

function get_navbar_footer() {


    return '<div class="footer">
        <div class="footer-align col-md-12">
    <div class="fixed-bg-footer"></div>
    <div class="container">
    <div class="row">
        <div class="col-xs-12">
            <div id="logo-footer">
                <a href="/"><img title="Maxbid leilões on line" alt="Maxbid leilões on line" src="/public/images/logo_rodape.png"></a>
            </div>
            <div id="box-menu-footer">
                <div class="menu-footer-barra">
                    <ul class="menu-footer">
                        <li><a href="/"><span>Página Inicial</span></a></li>
                        <li><span class="barra-separador">|</span></li>
                        <li><a href="' . site_url('quem-somos') . '"><span>Quem Somos</span></a></li>
                        <li><span class="barra-separador">|</span></li>
                        <li><a href="politica-privacidade"><span>Política de Uso</span></a></li>
                        <li><span class="barra-separador">|</span></li>
                        <li><a href="' . site_url('duvidas') . '"><span>Dúvidas</span></a></li>
                        <li><span class="barra-separador">|</span></li>
                        <li><a href="' . site_url('quero-vender') . '"><span>Quero Vender</span></a></li>
                        <li><span class="barra-separador">|</span></li>
                        <li><a data-trigger="cadastro" href="#"><span style="color: #fce603;">Cadastre-se</span></a></li>
                        <li><span class="barra-separador">|</span></li>
                        <li><a href="' . site_url('contato.html') . '"><span>Contato</span></a></li>
                   </ul>
                </div>
            </div>

        </div>
        </div>
        <div class="row">
        <div class="col-xs-12">
             <div id="address">
                <span class="text-address">Fone: (11) 4386 1020 | 4386 1030. Rua Doutor Ramos de Azevedo nº 159 - 3° andar</span><br>
                <span class="text-address">Salas 309 - CEP: 07012-020 - Guarulhos - São Paulo</span>
                <p><a href=""><img title="Maxbid leilões on line -  facebook" alt="Maxbid leilões on line -  facebook" class="img-face" src="/public/images/ico_face.jpg"></a><span class="text-email-contato">contato@maxbid.com.br</span></p>
             </div>
       
        <div class="col-md-12 text-copy">
            <p>MAXBID © 2014 - Todos os Direitos reservados</p>
        </div>
        </div>
         </div>

    <!-- FOOTER --> 

</div>
</div>
</div>';
}

function template_lang($str) {
    return $str;
}

/**
 * Formate CPF 
 * 
 * use para formatar cpf's automaticamente.
 *
 * 
 */
function formate_cpf($str) {

    if (strpos($str, '.')) {
        return str_replace(array('.', '-'), array('', ''), $str);
    }

    return substr($str, 0, 3) . '.' . substr($str, 3, 3) . '.' . substr($str, 6, 3) . '-' . substr($str, 9, 2);
}

function user_is_habilitado_lance($id_leilao) {
    $ci = & get_instance();
    if ($ci->user_model->loggedin()) {
        $key = hash('sha512', $ci->session->userdata('id') . $id_leilao);
        $row = $ci->db->get_where('habilitacao', array('CODIGO' => $key))->row();
        if ($row) {
            return true;
        }
    }

    return false;
}

if (!function_exists('isEnabled')) {

    function isEnabled($id, $leilao) {
        $ci = & get_instance();
        if ($ci->db->get_where('habilitacoes', array('USER_ID' => $id, 'LEILAO_ID' => $leilao))->num_rows() > 0) {
            return true;
        }
        return false;
    }

}

if (!function_exists('isUnlocked')) {

    function isUnlocked($id, $leilao) {
        $ci = & get_instance();
        if ($ci->db->get_where('habilitacoes', array('USER_ID' => $id, 'LEILAO_ID' => $leilao, 'BLOCKED' => 'N'))->num_rows() > 0) {
            return true;
        }
        return false;
    }

}



if (!function_exists('userData')) {

    function userData() {
        $ci = & get_instance();
        $info = new stdClass();
        $info->login = 'login';
        $info->loggedin = false;
        $info->id = 0;
        $info->favoritos = 0;
        $info->group = 'visitante';
        $user = $ci->user_manager->is_loggedin();

        if ($user) {
            $info->loggedin = true;
            $info->login = $user['login'];
            $info->token = $user['token'];
            $info->page = $user['page'];
            $info->id = $user['id'];
            $info->group = $user['group'];
        }
        return $info;
    }

}

function dif_horario($inicio, $fim) {

    if (is_php('5.2')) {
        $inicio = date_create_from_format('d/m/Y H:i:s', $inicio);
        $fim = date_create_from_format('d/m/Y H:i:s', $fim);
    } else {
        $inicio = DateTime::createFromFormat('d/m/Y H:i:s', $inicio);
        $fim = DateTime::createFromFormat('d/m/Y H:i:s', $fim);
    }


    $s = $inicio->diff($fim);
}

function extract_time($date) {

    $exp = preg_split('#\s#', $date);
    if (isset($exp['1'])) {
        //if (preg_match('#[0-9]{2}:[0-9]{2}:[0-9]{2}#', $exp['1'])) {
        return $exp['1'];
        // }
        return '00:00:00';
    }
    return '00:00:00';
}

function extract_data($date, $separator = '-') {

    $date = preg_split('#[\/\-\s\:]+#', $date);
    if (is_array($date) && count($date) > 3) {

        return $date['2'] . $separator . $date['1'] . $separator . $date['0'];
    }
    return $date;
}

if (!function_exists('auto_format_data')) {


    function auto_format_data($date1, $separator = '-', $separator_out = '-', $config = array()) {
        $configs = array_merge(array('name_month' => false,
            'name_month_short' => true), $config);


        if (preg_match('#^[0-9]{2}(/|\-)[0-9]{2}(/|\-)[0-9]{4}#', $date1)) {

            //  EUA Pattern
            return substr($date1, 6, 4) . $separator_out . substr($date1, 3, 2) . $separator_out . substr($date1, 0, 2);
        }

        if (preg_match('#^[0-9]{4}(/|\-)[0-9]{2}(/|\-)[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}#', $date1)) {
            $date = explode(' ', $date1);
            $date1 = $date['0'];
            $hour = $date['1'];

            $month = $configs['name_month'] ? get_name_month(substr($date1, 5, 2), $configs['name_month_short']) : substr($date1, 5, 2);

            return substr($date1, 8, 2) . $separator_out . $month . $separator_out . substr($date1, 0, 4) . ' ' . $hour;
        }

        if (preg_match('#^[0-9]{4}(/|\-)[0-9]{2}(/|\-)[0-9]{2}#', $date1)) {
            $month = $configs['name_month'] ? get_name_month(substr($date1, 5, 2), $configs['name_month_short']) : substr($date1, 5, 2);
            return substr($date1, 8, 2) . $separator_out . $month . $separator_out . substr($date1, 0, 4);
        }
    }

}

function compare_date_max($date1, $date2) {
    $mktime_d1 = false;
    $mktime_d2 = false;
    if (preg_match('#^[0-9]{4}(/|\-)[0-9]{2}(/|\-)[0-9]{2}#', $date1)) {
        $mktime_d1 = mktime(0, 0, 0, substr($date1, 5, 2), substr($date1, 8, 2), substr($date1, 0, 4));
    }

    if (preg_match('#^[0-9]{4}(/|\-)[0-9]{2}(/|\-)[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}#', $date1)) {
        $mktime_d1 = mktime(substr($date1, 11, 2), substr($date1, 14, 2), substr($date1, 17, 2), substr($date1, 5, 2), substr($date1, 8, 2), substr($date1, 0, 4));
    }


    if (preg_match('#^[0-9]{4}(/|\-)[0-9]{2}(/|\-)[0-9]{2}#', $date2)) {
        $mktime_d2 = mktime(0, 0, 0, substr($date2, 5, 2), substr($date2, 8, 2), substr($date2, 0, 4));
    }

    if (preg_match('#^[0-9]{4}(/|\-)[0-9]{2}(/|\-)[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}#', $date1)) {
        $mktime_d2 = mktime(substr($date2, 11, 2), substr($date2, 14, 2), substr($date2, 17, 2), substr($date2, 5, 2), substr($date2, 8, 2), substr($date2, 0, 4));
    }



    if ($mktime_d1 && $mktime_d2) {
        return ($mktime_d2 >= $mktime_d1) ? true : false;
    }

    return false;
}

function render_zoom_gallery($images) {

    $images = trim($images, ',');
    if (empty($images)) {
        return '';
    }

    if (preg_match('#,#', $images)) {
        $images = explode(',', $images);
    }

    if (!is_array($images)) {
        $images = array($images);
    }


    $gallery_zoom = '';
    $single = '';

    foreach ($images as $key => $img) {
        $cls = '';
        if ($key == 0) {
            $single = $img;
            $cls = ' active';
        }
        $gallery_zoom .= '
                      <a href="#" class="elevatezoom-gallery link-gallery-zoom ' . $cls . '" data-image="' . base_url('public/images/' . $img) . '" data-zoom-image="' . base_url('public/images/' . $img) . '">
                        <img src="' . base_url('public/images/' . $img) . '" width="95%" />
                      </a>';
    }

    $html_zoom = '<div class="box-container-img-zoom"><div class="box-img-zoom"><img id="zoom_img" src="' . base_url('public/images/' . $single) . '" data-zoom-image="' . base_url('public/images/' . $single) . '"/></div><div id="zoom_gallery">' . $gallery_zoom . '</div></div>';


    return $html_zoom;
}

function render_first_image($images) {

    $images = trim($images, ',');
    if (empty($images)) {
        return '';
    }

    if (preg_match('#,#', $images)) {
        $images = explode(',', $images);
    }

    if (!is_array($images)) {
        $images = array($images);
    }


    return (!empty($images['0']) && $images['0'] != "" ? $images['0'] : 'no_image.png');
}

function validate_cpf($cpf) {

    // Verifica se um número foi informado
    if (empty($cpf)) {
        return false;
    }

    // Elimina possivel mascara
    $cpf = preg_replace('[^0-9]', '', $cpf);
    $cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);

    // Verifica se o numero de digitos informados é igual a 11 
    if (strlen($cpf) != 11) {
        return false;
    }
    // Verifica se nenhuma das sequências invalidas abaixo 
    // foi digitada. Caso afirmativo, retorna falso
    else if ($cpf == '00000000000' ||
            $cpf == '11111111111' ||
            $cpf == '22222222222' ||
            $cpf == '33333333333' ||
            $cpf == '44444444444' ||
            $cpf == '55555555555' ||
            $cpf == '66666666666' ||
            $cpf == '77777777777' ||
            $cpf == '88888888888' ||
            $cpf == '99999999999') {
        return false;
        // Calcula os digitos verificadores para verificar se o
        // CPF é válido
    } else {

        for ($t = 9; $t < 11; $t++) {

            for ($d = 0, $c = 0; $c < $t; $c++) {
                $d += $cpf{$c} * (($t + 1) - $c);
            }
            $d = ((10 * $d) % 11) % 10;
            if ($cpf{$c} != $d) {
                return false;
            }
        }

        return true;
    }
}

function clear_cpf_cnpj($in) {
    $in = trim($in);
    return str_replace(array('.', '/', '-', '(', ')', '[', ']'), array('', '', '', '', '', '', ''), $in);
}

function validate_cnpj($cnpj) {
    $cnpj = clear_cpf_cnpj($cnpj);
    $sum = 0;
    if (empty($cnpj) || strlen($cnpj) != 14)
        return FALSE;
    else {
        if (check_fake($cnpj, 14))
            return FALSE;
        else {
            $rev_cnpj = strrev(substr($cnpj, 0, 12));
            for ($i = 0; $i <= 11; $i++) {
                $i == 0 ? $multiplier = 2 : $multiplier;
                $i == 8 ? $multiplier = 2 : $multiplier;
                $multiply = ($rev_cnpj[$i] * $multiplier);
                $sum = $sum + $multiply;
                $multiplier++;
            }
            $rest = $sum % 11;
            if ($rest == 0 || $rest == 1)
                $dv1 = 0;
            else
                $dv1 = 11 - $rest;
            $sub_cnpj = substr($cnpj, 0, 12);
            $rev_cnpj = strrev($sub_cnpj . $dv1);
            unset($sum);
            $sum = 0;
            for ($i = 0; $i <= 12; $i++) {
                $i == 0 ? $multiplier = 2 : $multiplier;
                $i == 8 ? $multiplier = 2 : $multiplier;
                $multiply = ($rev_cnpj[$i] * $multiplier);
                $sum = $sum + $multiply;
                $multiplier++;
            }
            $rest = $sum % 11;
            if ($rest == 0 || $rest == 1)
                $dv2 = 0;
            else
                $dv2 = 11 - $rest;if ($dv1 == $cnpj[12] && $dv2 == $cnpj[13])
                return TRUE;
            else
                return FALSE;
        }
    }
}

function check_fake($string, $length) {
    for ($i = 0; $i <= 9; $i++) {
        $fake = str_pad("", $length, $i);
        if ($string === $fake)
            return(1);
    }
}

if (!function_exists('get_text_status_leilao')) {


    function get_text_status_leilao($cod) {

        switch ($cod):

            case 1:
                return 'Aberto para Lances';
                break;
            case 2:
                return 'Em Loteamento';
                break;
            case 3:
                return 'em Divulgação';
                break;
            case 4:
                return 'Encerrado';
                break;
            case 5:
                return 'Cancelado';
                break;
            default :
                return 'Em definição';
                break;
        endswitch;
    }

}

function get_btn_seguir_oferta($row) {

    switch ($row->STATUS):

        case 1:

            if ($row->retirado == 'S') {
                return '<h3 class="label label-danger" style="width:100%; display:block; padding-top:5px;">RETIRADO</h3>';
            }

            if ($row->TIPO == 'DI') {
                return anchor(site_url('fale-conosco/proposta/' . $row->LEILAO_ID . '/' . $row->NUM_LOTE . '/'), 'Enviar proposta', 'class="btn btn-primary" style="margin-bottom:3px;"');
            }
            return
                    render_link_lote($row->codlote, $row->LEILAO_ID, '<span class="glyphicon glyphicon-ok-circle"></span> Seguir Oferta', 'class="btn btn-seguir-oferta"');


            break;
        case 2:
            return '';
            break;
        case 3:
            return 'Leilão <br>  em Divulgação';
            break;
        case 4:
            $btn = '';
            $style = '';

            if ($row->TIPO == 'DI') {
                return '';
            }
            if (isShowButtonProposta($row->datafim)) {

                $btn .= anchor(site_url('fale-conosco/proposta/' . $row->LEILAO_ID . '/' . $row->NUM_LOTE), 'Enviar proposta', 'class="btn btn-primary" style="margin-bottom:3px;"');
                $style = 'style="margin-bottom:0px;"';
            }


            $btn .=render_link_lote($row->codlote, $row->LEILAO_ID, '<span class="glyphicon glyphicon-ok-circle"></span> LOTE ENCERRADO', 'class="btn btn-danger" ' . $style);

            return $btn;



            break;
        case 5:
            return 'Leilão <br/> Cancelado';
            break;
        default :
            return 'Em definição';
            break;
    endswitch;
}

if (!function_exists('format_cnpj')) {

    function format_cnpj($cnpj) {
        return substr($cnpj, 0, 2) . '.' . substr($cnpj, 2, 3) . '.' . substr($cnpj, 5, 3) . '/' . substr($cnpj, 8, 4) . '-' . substr($cnpj, 12);
    }

}

function isShowButtonProposta($dataLote) {
    $days = 20;
    $data_lote = strtotime($dataLote);
    $data_now = time() - ($days * 86400);


    return $data_lote >= $data_now ? true : false;
}

function array_merge_recursive_distinct(array &$array1, array &$array2) {
    $merged = $array1;

    foreach ($array2 as $key => &$value) {
        if (is_array($value) && isset($merged [$key]) && is_array($merged [$key])) {
            $merged [$key] = array_merge_recursive_distinct($merged [$key], $value);
        } else {
            $merged [$key] = $value;
        }
    }

    return $merged;
}

function format_telefone($number) {


    if (empty($number)) {
        return '';
    }
    return '(' . substr($number, 0, 2) . ')' . substr($number, 2, 4) . '-' . substr($number, 6, 8);
}

function format_cnpj_cpf($number) {


    if (strlen($number) == 11) {

        return formate_cpf($number);
    }

    return format_cnpj($number);
}

function format_cep($number) {
    if (empty($number)) {
        return '';
    }
    return substr($number, 0, 5) . '-' . substr($number, 5);
}

function next_lote_id($array, $lote) {
    $_count = count($array);
    if ($_count == 0) {
        return false;
    }

    $index = array_search($lote, $array);
    return $index + 1 > ($_count - 1) ? false : $array[$index + 1];
}

function prev_lote_id($array, $lote) {

    $_count = count($array);
    if ($_count == 0) {
        return false;
    }

    $index = array_search($lote, $array);

    return $index - 1 < 0 ? false : $array[$index - 1];
}

function first_lote_id($array, $lote) {

    $_count = count($array);
    if ($_count == 0) {
        return false;
    }

    $code = $array['0'];

    return $code == $lote ? false : $code;
}

function last_lote_id($array, $lote) {

    $_count = count($array);
    if ($_count == 0) {
        return false;
    }

    $code = $array[$_count - 1];

    return $code == $lote ? false : $code;
}

function get_taxa($value) {

    $ci = & get_instance();
    $ci->load->model('Taxas_M');
    $taxa = $ci->Taxas_M->get_by('MAXIMO >= ' . $value, true);
    if ($taxa) {
        return $taxa->TAXA;
    }

    return '0.00';
}

function format_number_nfe($nfe_number) {

    return str_pad($nfe_number, 9, 0, STR_PAD_LEFT);
}

function get_uf_cidade($id) {
    $ci = & get_instance();
    $ci->db
            ->select('cd.*, ufs.id,ufs.nome as estado,ufs.uf')
            ->from('cidades as cd')
            ->join('estados as ufs', 'ufs.id=cd.estado')
            ->where(array('cd.id' => $id));
    $rs = $ci->db->get();

    return $rs->num_rows() > 0 ? $rs->row() : false;
}

function get_name_month($month, $short = true) {

    $months_array = array(
        1 => 'JANEIRO',
        2 => 'FEVEREIRO',
        3 => 'MARÇO',
        4 => 'ABRIL',
        5 => 'MAIO',
        6 => 'JUNHO',
        7 => 'JULHO',
        8 => 'AGOSTO',
        9 => 'SETEMBRO',
        10 => 'OUTUBRO',
        11 => 'NOVEMBRO',
        12 => 'DEZEMBRO');


    $getM = $months_array[(int) $month];

    return $short !== false ? substr($getM, 0, 3) : $getM;
}

if (!function_exists('render_link_lote')) {


    function render_link_lote($id, $id_leilao, $data, $extra = null, $return_href = false) {

        $_href = site_url('ver-lote/' . $id . '/' . $id_leilao);

        if ($return_href) {
            return $_href;
        }

        return anchor($_href, $data, $extra);
    }

}


if (!function_exists('generate_banners')) {


    function generate_banners($limit = 10) {

        $ci = & get_instance();

        $db = $ci->db;

        $data = $db->limit($limit)->order_by('ID', 'DESC')->where('ACTIVATE', 'S')->get('banners')->result();
        $data2 = $db->limit(1)->order_by('ID', 'DESC')->get('propa')->result();
        $_class_banner = count($data2) > 0 ? 'col-xs-9 col-md-7' : 'col-xs-9 col-md-9';
        if ($data) {
            $items = '';
            $ind = '';
            foreach ($data as $key => $row) {
                $image = trim($row->IMAGE, ',');
                if (strpos($image, ',')) {
                    $x_image = explode(',', $image);
                    $image = $x_image['0'];
                }
                $acitve = $key == 0 ? 'active' : '';
                $ind .= '<li data-target="#boxBanners" data-slide-to="' . $key . '" class="' . $acitve . '"></li>';
                $link_ = add_image('banners/' . $image, "title=\"Maxbid leilões on line - {$row->TITLE}\" alt=\"Maxbid leilões on line - {$row->TITLE}\" ");
                $_href = trim($row->LINK);
                if (!empty($_href)) {
                    $link_ = anchor($_href, $link_);
                }
                $items .= '<div class="item ' . $acitve . '">' . $link_ . '<div class="carousel-caption"></div></div>';
            }
            $banners = '<div class="box-banners"><div class="carousel slide" id="boxBanners" data-ride="carousel">
                  <ol class="carousel-indicators">' . $ind . '</ol><div class="carousel-inner">
                      ' . $items . '</div></div></div>';
            return '<div id="home-banner-box" class="' . $_class_banner . ' home-banners banners">' . $banners . '</div>';
        }

        return '';
    }

}



if (!function_exists('get_label_type_leilao')) {

    function get_label_type_leilao($str) {
        $options = array('C' => 'Compartilhado', 'DI' => 'Direto', 'EX' => 'Exclusivo');
        return $options[$str];
    }

}

function get_id_uf($uf) {
    $ci = & get_instance();
    $db = $ci->db;
    $r = $db->get_where('estados', array('UF' => trim($uf)));

    if ($r->num_rows() > 0) {
        return $r->row()->ID;
    }
    return $uf; //->row()->ID;
}

function get_id_city($str) {
    $ci = & get_instance();
    $db = $ci->db;
    $r = $db->get_where('cidades', array('SLUG' => url_slug($str)));
    if ($r->num_rows() > 0) {
        return $r->row()->ID;
    }
    return $str; //->row()->ID;
}

function url_slug($str, $options = array()) {
    // Make sure string is in UTF-8 and strip invalid UTF-8 characters
    $str = mb_convert_encoding((string) $str, 'UTF-8', mb_list_encodings());

    $defaults = array(
        'delimiter' => '-',
        'limit' => null,
        'lowercase' => true,
        'replacements' => array(),
        'transliterate' => false,
    );

    // Merge options
    $options = array_merge($defaults, $options);

    $char_map = array(
        // Latin
        'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
        'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
        'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
        'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
        'ß' => 'ss',
        'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
        'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
        'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
        'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
        'ÿ' => 'y',
        // Latin symbols
        '©' => '(c)',
        // Greek
        'Α' => 'A', 'Β' => 'B', 'Γ' => 'G', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => '8',
        'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => '3', 'Ο' => 'O', 'Π' => 'P',
        'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'PS', 'Ω' => 'W',
        'Ά' => 'A', 'Έ' => 'E', 'Ί' => 'I', 'Ό' => 'O', 'Ύ' => 'Y', 'Ή' => 'H', 'Ώ' => 'W', 'Ϊ' => 'I',
        'Ϋ' => 'Y',
        'α' => 'a', 'β' => 'b', 'γ' => 'g', 'δ' => 'd', 'ε' => 'e', 'ζ' => 'z', 'η' => 'h', 'θ' => '8',
        'ι' => 'i', 'κ' => 'k', 'λ' => 'l', 'μ' => 'm', 'ν' => 'n', 'ξ' => '3', 'ο' => 'o', 'π' => 'p',
        'ρ' => 'r', 'σ' => 's', 'τ' => 't', 'υ' => 'y', 'φ' => 'f', 'χ' => 'x', 'ψ' => 'ps', 'ω' => 'w',
        'ά' => 'a', 'έ' => 'e', 'ί' => 'i', 'ό' => 'o', 'ύ' => 'y', 'ή' => 'h', 'ώ' => 'w', 'ς' => 's',
        'ϊ' => 'i', 'ΰ' => 'y', 'ϋ' => 'y', 'ΐ' => 'i',
        // Turkish
        'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
        'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',
        // Russian
        'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
        'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
        'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
        'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
        'Я' => 'Ya',
        'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
        'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
        'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
        'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
        'я' => 'ya',
        // Ukrainian
        'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
        'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',
        // Czech
        'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
        'Ž' => 'Z',
        'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
        'ž' => 'z',
        // Polish
        'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
        'Ż' => 'Z',
        'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
        'ż' => 'z',
        // Latvian
        'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
        'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
        'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
        'š' => 's', 'ū' => 'u', 'ž' => 'z'
    );

    // Make custom replacements
    $str = preg_replace(array_keys($options['replacements']), $options['replacements'], $str);

    // Transliterate characters to ASCII
    if ($options['transliterate']) {
        $str = str_replace(array_keys($char_map), $char_map, $str);
    }

    // Replace non-alphanumeric characters with our delimiter
    $str = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $str);

    // Remove duplicate delimiters
    $str = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $str);

    // Truncate slug to max. characters
    $str = mb_substr($str, 0, ($options['limit'] ? $options['limit'] : mb_strlen($str, 'UTF-8')), 'UTF-8');

    // Remove delimiter from ends
    $str = trim($str, $options['delimiter']);

    return $options['lowercase'] ? mb_strtolower($str, 'UTF-8') : $str;
}

function normalize_fields_to_db($f) {

    return to_url_friend($f, '-', '_');
}

function money_db($str) {
    $str = clear_number($str);
    $_length = strlen($str);
    $dec = substr($str, 0, ($_length - 2));
    $cent = substr($str, -2);
    return $dec . '.' . $cent;
}

function replace_hour($datatime, $hour_replace) {

    $eexplode = explode(' ', $datatime);
    $hour = $hour_replace . ':00';
    if (preg_match('#^[0-9]{2}:[0-9]{2}:[0-9]{2}$#', $hour_replace)) {
        $hour = $hour_replace;
    }
    return $eexplode['0'] . ' ' . $hour;
}

function str_num_lote_pad($str, $length = 4) {
    return str_pad((int) $str, $length, 0, STR_PAD_LEFT);
}

function explodeImages($str) {
    $str = trim($str, ',');
    return preg_split('/[\s,]/', $str);
}

function render_to_gallery_painel($str) {

    $data = explodeImages($str);

    if (!is_array($data)) {
        $data = array($data);
    }
    $images = '[';
    foreach ($data as $key => $image):
        if ($key > 0) {
            $images .=',';
        }

        $images .= '{"href":"/public/images/lotes/' . $image . '"}';
    endforeach;
    $images .= ']';
    echo $images;
}

function hasAutoLance($u_id) {
    $ci = & get_instance();
    $ci->load->model('Lances_Automaticos_M');
    $db = $ci->Lances_Automaticos_M;

    $lcas = $db->get_by(array('USER_ID' => $u_id));

    $lances = array();
    if ($lcas) {
        foreach ($lcas as $row):
            $lances[] = $row->LOTE_ID;
        endforeach;
    }


    return $lances;
}

function format_money_db($str) {

    return str_replace(',', '.', str_replace('.', '', $str));
}

function mask_email($email) {


    $emails = preg_split('#@#', $email);
    $max = strlen($emails['1']);
    $part = '';
    for ($i = 0; $i < $max; $i++) {

        if (preg_match('#[0-9A-Za-z]#', $emails['1'][$i])) {
            $part .='x';
        } else {
            $part .= $emails['1'][$i];
        }
    }

    return $emails['0'] . '@' . $part;
}

function exceptions_uri($match) {

    if (!is_array($match)) {
        $match = array($match);
    }

    foreach ($match as $val) {
        $val = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $val));
        if (preg_match('#^' . $val . '$#', uri_string())) {
            return true;
        }
    }

    return false;

    // Does the RegEx match?
}

function lang_system($index) {
    return Utils::message($index);
}

function mask_hour($str) {
    if (!preg_match('#:#', $str)) {
        $_length = strlen($str);
        if ($_length == 6) {
            return substr($str, 0, 2) . ':' . substr($str, 2, 2) . ':' . substr($str, 4);
        }
        return substr($str, 0, 2) . ':' . substr($str, 2) . ':00';
    }

    return $str;
}

function _disconect() {
    file_put_contents('disconec.txt', 'DIsocan');
}

if (!function_exists('render_image_leilao')) {

    function render_image_leilao($obj) {
        if (!is_object($obj)) {
            return '';
        }
        $imageLeilao = trim($obj->IMAGEM);
        $imageLogo = $obj->LOGO;
        $leilao_image = false;
        $patternImages = '#(\.gif|\.jpg|\.png|\.jpeg)#';
        if (preg_match($patternImages, strtolower($imageLogo))) {
            $leilao_image = 'comitentes/' . $imageLogo;
        }
        if (preg_match($patternImages, strtolower($imageLeilao))) {
            $leilao_image = 'leiloes/' . $imageLeilao;
        }
        if ($leilao_image === false) {
            $leilao_image = 'no_image.jpg';
        }
        return add_image($leilao_image, 'class="img-leilao" title="leilões on line - ' . $obj->TITLE . '" alt="leilões online - ' . $obj->TITLE . '"');
    }

}


